package com.hlkj.baojin.dao.repository;

import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.constant.BaseRepository;
import com.hlkj.baojin.entity.Duty;
import com.hlkj.baojin.entity.dto.DutySearchDto;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.utils.PatternUtil;
import com.hlkj.baojin.utils.bean.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author HULIN
 * @created with: baojin
 * @package com.hlkj.baojin.dao.repository
 * @description:
 * @date 2019/1/29 13:28
 * @modified By:
 * @Copyright © 2018 HAILIANG Info. Tech Ltd. All rights reserved.
 */
@Component
public class DutyRepository extends BaseRepository<Duty> {

    public DutyRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    public void updateCompanyNotNull(Duty duty) {
        Duty dutyDB = new Duty();
        dutyDB.setId(duty.getId());
        super.updateByBean(dutyDB, duty);
    }

    public ModelList<Duty> getDuty(DutySearchDto dutySearchDto) {
        Query query = new Query();

        if (StringUtils.isNotBlank(dutySearchDto.getMultiCondition())) {
            Pattern pattern = PatternUtil.fuzzyMatch(dutySearchDto.getMultiCondition());
            query.addCriteria(new Criteria().orOperator(
                    Criteria.where("name").regex(pattern),
                    Criteria.where("mobilePhone").regex(pattern)));
        }

        if (dutySearchDto.getDutyStatus() != null) {
            query.addCriteria(Criteria.where("dutyStatus").is(dutySearchDto.getDutyStatus()));
        }
        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));
        query.with(new Sort(Sort.Direction.DESC, "createTime"));

        query.with(new Page(dutySearchDto.getPage(), dutySearchDto.getSize()));

        List<Duty> dutyList = mongoTemplate.find(query, Duty.class);
        long count = mongoTemplate.count(query, Duty.class);

        ModelList<Duty> dutyModelList = new ModelList<>(dutyList, count);

        return dutyModelList;
    }
}
